package com.jiyi.activity.datainput.jm;

import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.activity.datainput.DIBasePicActivity;
import com.jiyi.bean.datainput.DataInputWBWBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.inteface.DownloadPicOverInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.picselect.PicSelectConstans;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class DataInputWBWActivity extends DIBasePicActivity implements DownloadPicOverInterface{

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.spBWCL)
	Spinner spBWCL;
	@BindView(R.id.spFDBY)
	Spinner spFDBY;
	@BindView(R.id.spPSKL)
	Spinner spPSKL;
	@BindView(R.id.spTL)
	Spinner spTL;
	@BindView(R.id.spLL)
	Spinner spLL;
	
	ArrayAdapter<String> stateBWCLAdapter,stateFDBYAdapter,statePSKLAdapter,stateTLAdapter,stateLLAdapter;
	Dialog dialog;
	String build_no;
	
	@BindView(R.id.gvPic)
	GridView gvPic;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_data_input_wbw);
		ButterKnife.bind(this);
		init();
	}
	
	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		super.onDestroy();
	}
	
	public void init() {
		getIntentData();
		setTop();
		setAdapter();
		getData();
		super.setDownloadPicOverInterface(this);
	}
	
	private void getIntentData() {
		build_no = getIntent().getStringExtra("build_no");
	}

	private void setTop() {
		tvTitle.setText("外保温材料");
		tvSearch.setCompoundDrawables(null, null, null, null);
		tvSearch.setText("保存");
	}
	
	private void setAdapter() {
		stateBWCLAdapter = new ArrayAdapter<String>(this,R.layout.item_spinner, getResources().getStringArray(R.array.yes_no));
		spBWCL.setAdapter(stateBWCLAdapter);
		stateFDBYAdapter = new ArrayAdapter<String>(this,R.layout.item_spinner, getResources().getStringArray(R.array.yes_no));
		spFDBY.setAdapter(stateFDBYAdapter);
		statePSKLAdapter = new ArrayAdapter<String>(this,R.layout.item_spinner, getResources().getStringArray(R.array.yes_no));
		spPSKL.setAdapter(statePSKLAdapter);
		stateTLAdapter = new ArrayAdapter<String>(this,R.layout.item_spinner, getResources().getStringArray(R.array.yes_no));
		spTL.setAdapter(stateTLAdapter);
		stateLLAdapter = new ArrayAdapter<String>(this,R.layout.item_spinner, getResources().getStringArray(R.array.yes_no));
		spLL.setAdapter(stateLLAdapter);
	}
	
	@OnClick({ R.id.tvBack ,R.id.tvSearch})
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvSearch:
			//保存
//			doPost();
			downloadImage();
			break;
		default:
			break;
		}
	}
	
	private void doPost() {
		String url = "";
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("build_info_id", build_no);
		params.put("is_inflammable", spBWCL.getSelectedItemPosition()+"");
		params.put("seal_is_lax", spFDBY.getSelectedItemPosition()+"");
		params.put("breakage_of_cracking", spPSKL.getSelectedItemPosition()+"");
		params.put("fall_off", spTL.getSelectedItemPosition()+"");
		params.put("bareness", spLL.getSelectedItemPosition()+"");
		params.put("build_info_id", build_no);
		url = WebApi.DATA_INPUT_WBWCL;
		Log.e("params   ", params.toString());
		
		PostFormBuilder postForm = OkHttpUtils.post().url(url);
		postForm.params(params);
		// 图片数组
		int size = PicSelectConstans.publish_pics.size();
		File file;
		for (int i = 0; i < size; i++) {
			if (PicSelectConstans.publish_pics.get(i).contains("http")) {
				continue;
			}
			file = new File(PicSelectConstans.publish_pics.get(i));
			postForm.addFile("image[]", "pic" + (i + 1) + ".jpg", file);
		}

		dialog = showDialog(dialog);
		postForm.build().execute(new StringCallback() {

			@Override
			public void onError(Call arg0, Exception exception, int arg2) {
				hideDialog(dialog);
				ToastUtil.getInstances().showMsg(exception.getMessage());
			}

			@Override
			public void onResponse(String result, int arg1) {
				try {
					JSONObject obj = new JSONObject(result);
					String status = obj.getString("status");
					String info = obj.getString("info");
					if (status.equals("200")) {
						ToastUtil.getInstances().showMsg(info);
						finish();
					} else if (status.equals("404") && info.contains("尚未登录")) {
						ToastUtil.getInstances().showMsg(
								"尚未登录或该用户在其他地方登录，请重新登录！");
						// 清除环信登录
						UserHelp.getInstance().clearUser(AppBase.Context,
								true);
						return;
					} else {
						ToastUtil.getInstances().showMsg(info);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} finally {
					hideDialog(dialog);
				}
			}
		});
	}
	
	
	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("build_info_id", build_no);

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.DATA_INPUT_WBW_READ, "",
				params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								Log.e("dfdsf   ", result);
								DataInputWBWBean temp = new Gson().fromJson(data,
										DataInputWBWBean.class);
								if (temp == null) {
									temp = new DataInputWBWBean();
									temp.setBareness(0);
									temp.setBreakage_of_cracking(0);
									temp.setBuild_info_id(build_no);
									temp.setFall_off(0);
									temp.setIs_inflammable(0);
									temp.setSeal_is_lax(0);
								}
								setData(temp);
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}
	
	void setData(DataInputWBWBean temp){
		spBWCL.setSelection(temp.getIs_inflammable());
		spFDBY.setSelection(temp.getSeal_is_lax());
		spPSKL.setSelection(temp.getBreakage_of_cracking());
		spTL.setSelection(temp.getFall_off());
		spLL.setSelection(temp.getBareness());
		
		PicSelectConstans.publish_pics = temp.getImage() == null ? new ArrayList<String>() : temp.getImage();
		refreshAdapter(gvPic);
	}
	
	@Override
	public void post() {
		doPost();
	}
}
